package com.yonyou.wdt.job;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yonyou.wdt.entity.OpenApiURLEnum;
import com.yonyou.wdt.entity.QueryDto;
import com.yonyou.wdt.job.config.BaseConfig;
import com.yonyou.wdt.qimenmodel.qimencloud.api.DefaultQimenCloudClient;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.request.WdtRefundOrderQueryRequest;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.request.WdtRefundQueryRequest;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.response.WdtRefundOrderQueryResponse;
import com.yonyou.wdt.qimenmodel.qimencloud.api.scenehu3cgwt0tc.response.WdtRefundQueryResponse;
import com.yonyou.wdt.service.YonsuiteService;
import com.yonyou.wdt.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class WdtQmRefundToYsReceiveRed extends BaseConfig {


    private static final Logger logger = LoggerFactory.getLogger(WdtQmRefundToYsReceiveRed.class);
    private final WdtConfigProperties configProperties;
    @Resource
    private YonsuiteService yonsuiteService;
    private static final String JOB_CLASS="maoEr008";
    @Autowired
    public WdtQmRefundToYsReceiveRed(WdtConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

    @XxlJob("WdtQmRefundToYsReceiveRed")
    public ReturnT<String> wdtQmSaleReturnToYsSaleReturn(String params) throws Exception {
        String param = XxlJobHelper.getJobParam();
        Map<String, Object> map = new HashMap<>();
        if (param != null && !"".equals(param)) {
            if (param.contains("&")) {
                List<String> timeRange = Arrays.asList(param.split("&"));
                if (timeRange.size() == 3) {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                    map.put("shop_no", timeRange.get(2));
                } else {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                    map.put("shop_no", timeRange.get(2));
                    map.put("warehouse_no", timeRange.get(3));
                }
            } else {
                List<String> timeRange = Arrays.asList(param.split("\\|"));
                if (timeRange.size() == 2) {
                    map.put("Start", timeRange.get(0));
                    map.put("End", timeRange.get(1));
                } else {
                    map.put("refund_no", timeRange.get(0));
                }
            }
        } else {
            // 默认查询前一天的数据
            map.put("Start", DateUtils.getStartDateBy10m());
            map.put("End", DateUtils.getEndDateBy10m());
        }
        String dateStr = null;
        if (map.get("Start") != null && map.get("End") != null) {
            dateStr = map.get("Start").toString() + map.get("End").toString();
        }

        // 处理相关业务
        QueryDto dto = new QueryDto();
        dto.setTenantId(getYsTenantId());
        dto.setAppKey(getYsAppKey());
        dto.setAppSecret(getYsAppSecret());
        // 获取YS系统租户动态域名信息
        ReturnT<String> isReturn2 = getYsDynamicDomainName(JOB_CLASS,dto);
        // 域名获取失败
        if (isReturn2 != null) return isReturn2;
        try {
           List<JSONObject> toReceiveRedList = sendWdtByQm(map, dto);
            // jsonObjectList = new ArrayList<>();
            Integer successCount = 0;
            Integer failCount = 0;
            // jsonObjectList = new ArrayList<>();
            // 解析数据，组装YS请求参数
            if (!toReceiveRedList.isEmpty()) {
                // 查询YS仓库档案列表
                // HashMap<String, String> ckData = getCkData(dto, yonsuiteService);
                if (!toReceiveRedList.isEmpty()) {
                    for (int i = 0; i < toReceiveRedList.size(); i++) {
                        JSONObject jsonObject = toReceiveRedList.get(i);
                        Map<String, Object> ysSaveParam = assembleReceiveYsParams(jsonObject, dto);
                        JSONObject response = yonsuiteService.receivableSace(ysSaveParam, dto);
                        if (null != response && "200".equals(response.getStr("code"))) {
                            logger.info("旺店通仅退款单保存YS应收发票红成功");
                            logger.error("旺店通销售退货保存YS销售退货失败：{}", response.getOrDefault("message", ""));
                            InsertLogger(JOB_CLASS, null, "1", "旺店通销售退货保存YS销售退货失败" + response.getJSONObject("data").getStr("code") + "成功");

                        } else {
                            logger.error("旺店通仅退款单保存YS应收发票红失败：{}", response.getOrDefault("message", ""));
                            logger.error("旺店通销售退货保存YS销售退货失败：{}", response.getOrDefault("message", ""));
                            InsertLogger(JOB_CLASS, null, "1", "旺店通销售退货保存YS销售退货失败" + response.getJSONObject("data").getStr("code") + "成功");

                        }
                        // 处理YS接口调用频率问题
                        // 调用YS接口保存数据
                        this.APICurrentLimiting(OpenApiURLEnum.RECEIVABLE_SAVE, 19);

                    }

                }
                Thread.sleep(1000);
                InsertLogger(JOB_CLASS, null, "0", "当前时间段：" + dateStr + ",旺店通销售退货一共" + toReceiveRedList.size() + "条,保存YS销售退货成功:" + successCount + "条，失败:" + failCount + "条。");
            }
        } catch (Exception e) {
            logger.error("Error occurred", e);
            logger.error("旺店通销售退货同步YS销售退货失败，{}", e.getMessage());
            InsertLogger(JOB_CLASS,null, "0", "旺店通销售退货同步YS销售退货失败" + e.getMessage());
            return ReturnT.FAIL;
        }
        logger.info("  --  旺店通销售退货同步YS销售退货任务执行完成  --  ");
        return ReturnT.SUCCESS;
    }

    private Map<String, Object> assembleReceiveYsParams(JSONObject jsonObject, QueryDto dto) throws Exception {
        Map<String, Object> saleReturnSaveMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        // 添加表头
        String custCode=jsonObject.getStr("shop_no");
        /*String orgCode=orgAndWarehouseOrg.orgId;*/
        String orgCode="";
        HashMap<String, Object> shopQuery = new HashMap<>();
        shopQuery.put("shopCode",custCode);
        JSONObject entries = yonsuiteService.shopOrgQuery(shopQuery, dto);
        JSONObject responseJson = entries.getJSONObject("data").getJSONObject("response");
        if ("200".equals(responseJson.getStr("code"))) {
            orgCode = responseJson.getStr("orgCode");
        }else {
            InsertLogger( JOB_CLASS,jsonObject.getStr("src_order_no"), "0", "当前店铺：" + jsonObject.getStr("shop_no") + "在租户：" + dto.getTenantId() + "未配置店铺组织映射关系");
            logger.error("当前店铺：" + custCode + "在租户：" + dto.getTenantId() + "未配置店铺组织映射关系");
            return null;
        }
        saleReturnSaveMap.put("direction", -1);//单据方向
        saleReturnSaveMap.put("code", jsonObject.getStr("refund_no"));
        saleReturnSaveMap.put("financeOrgCode", orgCode);//开票组织编码
        saleReturnSaveMap.put("billDate", jsonObject.getStr("modified"));  // 单据日期
        saleReturnSaveMap.put("oriCurrencyCode", "CNY");  //币种编码
        saleReturnSaveMap.put("bustypeCode", "ar_invoice");  // 业务组织编码
        saleReturnSaveMap.put("orgCode", orgCode);  // 业务组织编码
        saleReturnSaveMap.put("customerCode", custCode);  //客户编码
        saleReturnSaveMap.put("exchangeRateTypeCode", "01");  //汇率类型编码
        saleReturnSaveMap.put("exchangeRate", 1);  //汇率
        saleReturnSaveMap.put("objectType", 1);  //往来对象类型
        saleReturnSaveMap.put("exchangeRateDate", jsonObject.getStr("modified"));  // 汇率日期

        saleReturnSaveMap.put("_status", "Insert");  // 操作标识

        JSONArray items = jsonObject.getJSONArray("refund_order_list");
        // ==========子表============
        JSONArray details = new JSONArray();
        BigDecimal payMoney=BigDecimal.ZERO;
        for (Object element : items) {
            JSONObject item = (JSONObject) element;
            // 获取物料编码
            String product = item.getStr("spec_no");
            // 获取Redis中物料档案信息
            JSONObject redisPrJson = (JSONObject) RedisUtils.get(dto.getAppKey() + ":" + product);
			/*if (redisPrJson == null) {
				// 保存同步错误日志，未找到对应物料档案信息
				logger.error("存在未同步YS系统物料数据：{}，请同步后重试", product);
				return null;
			}*/
            if (null != RedisUtils.get(dto.getTenantId() + ":product:" + product)) {
                redisPrJson = (JSONObject) RedisUtils.get(dto.getTenantId() + ":product:" + product);
            }
            if (redisPrJson == null) {
                logger.error("旺店通企业版仅退款售后单：" + jsonObject.getStr("refund_no") + "存在未同步YS系统物料数据" + product + "，请同步后重试");
                InsertLogger(JOB_CLASS,jsonObject.getStr("refund_no"), "0", "旺店通企业版仅退款售后单：" + jsonObject.getStr("src_order_no") + "存在未同步YS系统物料数据" + product + "，请同步后重试");
                // saveLog(productItem.getStr("sku_id"), refundJson.getStr("src_order_no"), "存在未同步至YS系统物料：" + productItem.getStr("sku_id"), dto, "0", DataConnectionTypeEnum.AFTER_SALES_ORDERS_TOYS_SALES_OUT.getCode());
                return null;
            }
            String unitId = redisPrJson.getStr("unitId") != null ? redisPrJson.getStr("unitId") : null;
            if (unitId == null) {
                logger.error("仅退款售后单：" + jsonObject.getStr("src_order_no") + "存在未维护单位物料，请维护后重试");
                InsertLogger(JOB_CLASS,jsonObject.getStr("src_order_no"), "0", "存在未维护单位物料，请维护后重试");

                // saveLog(productItem.getStr("sku_id"), refundJson.getStr("src_order_no"), "存在未维护单位物料，请维护后重试", dto, "0", DataConnectionTypeEnum.AFTER_SALES_ORDERS_TOYS_SALES_OUT.getCode());
            }
            HashMap<String, Object> saleOutDetail = new HashMap<>();
            // ===========子表============
            // 添加表体数据
            JSONObject saleReturnDetailsJson = new JSONObject();
            saleReturnDetailsJson.put("customerCode", custCode);  // 客户编码
            saleReturnDetailsJson.put("materialCode", product);  // 物料编码
            saleReturnDetailsJson.put("materialCode", product);  // 物料编码
            saleReturnDetailsJson.put("_status", "Insert");  // 操作标识
            saleReturnDetailsJson.put("orgCode", orgCode);  //业务组织编码
            BigDecimal qty = item.getBigDecimal("refund_num");
            saleReturnDetailsJson.put("quantity", qty.negate());  //数量
            BigDecimal saleAmount = item.getBigDecimal("total_amount");

            saleReturnDetailsJson.put("oriTaxIncludedAmount", saleAmount.negate());  // 含税金额

            // 税率
            BigDecimal outTaxrate = redisPrJson.containsKey("outTaxrate_name") ? redisPrJson.getBigDecimal("outTaxrate_name") : BigDecimal.ZERO;
            saleReturnDetailsJson.put("taxRate", outTaxrate);  // 税目税率，);  // 税率，传id或者code
            BigDecimal taxAmount = BigDecimal.ZERO;
            if (!"0".equals(outTaxrate.toString())) {
                taxAmount = saleAmount.divide(outTaxrate.divide(new BigDecimal(100)).add(new BigDecimal(1)), 4, RoundingMode.HALF_UP).multiply(outTaxrate.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)).setScale(2, RoundingMode.HALF_UP);
            }
            saleReturnDetailsJson.put("oriTaxAmount", taxAmount.negate());  // 税额  BigDecimal
            details.add(saleReturnDetailsJson);
        }
        saleReturnSaveMap.put("bodyItem", details);
        data.put("data", saleReturnSaveMap);
        //ReSubmitUtil.resubmitCheckKey(data);
        return data;
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 旺店通数据分组
     * @Date 10:21 2023/5/15
     * @Param
     **/
    private List<JSONObject> groupBy(List<JSONObject> responseList) {

        List<JSONObject> resultList = new ArrayList<>();
        try {
            Map<String, List<JSONObject>> createdDateMap = responseList.stream().collect(Collectors.groupingBy(json -> json.getStr("modified").substring(0, 10)));
            createdDateMap.forEach((payTime, createdValue) -> {
                Map<String,Map<String, List<JSONObject>>> collect = createdValue.stream().collect(Collectors.groupingBy(json -> json.getStr("shop_no"), Collectors.groupingBy(json -> json.getStr("warehouse_no"))));
                collect.forEach((shopNo, warehouseMap) -> {
                    warehouseMap.forEach((warehouseNo, warehouseItems) ->{
                        List<JSONObject> allItems = warehouseItems.stream().flatMap(element -> element.getJSONArray("refund_order_list").stream()).map(o -> (JSONObject) o).collect(Collectors.toList());
                        Map<String, List<JSONObject>> detailsListGoodsIdGroupMap = allItems.stream().collect(Collectors.groupingBy(json -> json.getStr("goods_no")));
                        JSONObject resultJson = new JSONObject();
                        List<JSONObject> itemsListResultList = detailsListGoodsIdGroupMap.entrySet().stream().map(entry -> {
                            List<JSONObject> items = entry.getValue();
                            BigDecimal qtyNew = items.stream().map(json -> json.getBigDecimal("stockin_num")).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal saleAmountNew = items.stream().map(json -> json.getBigDecimal("total_amount")).reduce(BigDecimal.ZERO, BigDecimal::add);

                            JSONObject theFirstItem = items.isEmpty() ? new JSONObject() : items.get(0);
                            theFirstItem.put("stockin_num", qtyNew);
                            theFirstItem.put("total_amount", saleAmountNew);
                            return theFirstItem;
                        }).collect(Collectors.toList());
                        resultJson.put("shop_no", shopNo);
                        resultJson.put("modified", payTime);
                        resultJson.put("warehouse_no", warehouseNo);
                        resultJson.put("refund_order_list", itemsListResultList);
                        resultList.add(resultJson);
                    });
                });
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    /**
     * @return
     * @Author Huangwb
     * @Description 组装YS请求数据
     * @Date 14:34 2023/5/17
     * @Param
     **/
    private Map<String, Object> assembleYsParams(JSONObject jsonObject, QueryDto dto) throws Exception {
        Map<String, Object> saleReturnSaveMap = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        // ==========主表============
        // 添加表头
        String custCode = jsonObject.getStr("shop_no");
        /*String orgCode=orgAndWarehouseOrg.orgId;*/
        //String orgCode = "20";
        Object o = RedisUtils.get(dto.getTenantId() + ":cust:" + custCode);
        if(o==null){
            // 保存同步错误日志，未找到对应客户档案信息
            logger.error("存在未同步YS系统客户数据：{}，请同步后重试", custCode);
            InsertLogger(JOB_CLASS,null, "0", "存在未同步YS系统客户数据："+custCode+"，请同步后重试");
            return null;
        }
        String orgCode = JSONUtil.parseObj(o).getStr("createOrgCode");//管理组织
        //saleReturnSaveMap.put("resubmitCheckKey", saleOutCode + "20230818");  // 幂等性
        saleReturnSaveMap.put("salesOrgId", orgCode);  // 销售组织
        String refundNo = jsonObject.getStr("refund_no");
        saleReturnSaveMap.put("code", refundNo);  // 单据编号
        saleReturnSaveMap.put("agentId", custCode);  // 客户
        saleReturnSaveMap.put("transactionTypeId", "RET001");  // 交易类型
        //saleReturnSaveMap.put("bizFlow", bizFlow);  // 流程ID （2C）
        // 单据日期-修改时间
	/*	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String modified = format.format(jsonObject.getStr("modified"));*/
        saleReturnSaveMap.put("vouchdate", jsonObject.getStr("modified"));  // 单据日期
        saleReturnSaveMap.put("settlementOrgId", orgCode);  // 开票组织
        saleReturnSaveMap.put("currency", "CNY");  // 币种
        saleReturnSaveMap.put("exchangeRateType", "01");  // 汇率类型
        saleReturnSaveMap.put("natCurrency", "CNY");  // 本币
        saleReturnSaveMap.put("exchRate", 1);  // 汇率
        saleReturnSaveMap.put("taxInclusive", true);  // 单价含税
        saleReturnSaveMap.put("saleReturnSourceType", "NONE");  // 退货类型
        saleReturnSaveMap.put("invoiceAgentId", custCode);  // 开票客户
        saleReturnSaveMap.put("_status", "Insert");  // 操作标识
        HashMap<String, Object> remarkMap = new HashMap<>();
        remarkMap.put("remark", "旺店通接口同步");  // 备注
        saleReturnSaveMap.put("saleReturnMemo", remarkMap);  // 备注
        JSONArray items = jsonObject.getJSONArray("refund_order_list");
        // ==========子表============
        JSONArray details = new JSONArray();
        BigDecimal payMoney = BigDecimal.ZERO;
        for (Object element : items) {
            JSONObject item = (JSONObject) element;
            // 获取物料编码
            String product = item.getStr("goods_no");
            // 获取Redis中物料档案信息
            JSONObject redisPrJson = (JSONObject) RedisUtils.get(dto.getTenantId() + ":product:" + product);
            if (redisPrJson == null) {
                // 保存同步错误日志，未找到对应物料档案信息
                logger.error("存在未同步YS系统物料数据：{}，请同步后重试", product);
                InsertLogger(JOB_CLASS,refundNo, "0", "存在未同步YS系统物料数据：" + product + "，请同步后重试");
                return null;
            }
            String unitId = redisPrJson.getStr("unitId") != null ? redisPrJson.getStr("unitId") : null;
            if (unitId == null) {
                logger.error("售后单：" + refundNo + "存在未维护单位物料，请维护后重试");
                InsertLogger(JOB_CLASS,refundNo, "0", "存在未维护单位物料，请维护后重试");
            }
            // ===========子表============
            // 添加表体数据
            JSONObject saleReturnDetailsJson = new JSONObject();
            saleReturnDetailsJson.put("productId", product);  // 商品，传id或者code
            saleReturnDetailsJson.put("skuId", product);  // 商品SKU，传id或者code
            saleReturnDetailsJson.put("unitExchangeType", 1);  // 浮动换算率（销售）int
            saleReturnDetailsJson.put("unitExchangeTypePrice", 1);  // 浮动换算率（计价）int
            saleReturnDetailsJson.put("taxId", redisPrJson.getStr("outTaxrate") != null ? redisPrJson.getStr("outTaxrate") : "TE");  // 税目税率，);  // 税目税率，传id或者code



            BigDecimal saleAmount = BigDecimal.ZERO;
            BigDecimal outTaxrate;
            BigDecimal unitPriceIncludingTax = BigDecimal.ZERO;
            BigDecimal taxAmount = BigDecimal.ZERO;
            BigDecimal noTaxSaleAmount = BigDecimal.ZERO;
            BigDecimal taxFreeUnitPrice = BigDecimal.ZERO;
            BigDecimal qty = item.getBigDecimal("stockin_num");
            // 金额计算：

            if (qty.compareTo(BigDecimal.ZERO)>0){
                // 金额
                saleAmount = item.getBigDecimal("total_amount");
                payMoney.add(saleAmount);
                // 税率
                outTaxrate = redisPrJson.containsKey("outTaxrate_name") ? redisPrJson.getBigDecimal("outTaxrate_name") : BigDecimal.ZERO;
                // 含税单价
                unitPriceIncludingTax = saleAmount.divide(qty, 4, RoundingMode.HALF_UP);
                // 税额
                if (!"0".equals(outTaxrate.toString())) {
                    taxAmount = saleAmount.divide(outTaxrate.divide(new BigDecimal(100)).add(new BigDecimal(1)), 4, RoundingMode.HALF_UP).multiply(outTaxrate.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)).setScale(2, RoundingMode.HALF_UP);
                    // taxAmount = saleAmount.multiply(outTaxrate.divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP));
                }
                // 无税金额
                noTaxSaleAmount = saleAmount.subtract(taxAmount);
                // 无税单价
                taxFreeUnitPrice = noTaxSaleAmount.divide(BigDecimal.valueOf(Double.parseDouble(String.valueOf(qty))), 4, RoundingMode.HALF_UP);
            }



            saleReturnDetailsJson.put("stockOrgId", "01");  // 库存组织，传id或者code
            saleReturnDetailsJson.put("iProductAuxUnitId", unitId);  // 销售单位，传id或者code
            saleReturnDetailsJson.put("iProductUnitId", unitId);  // 计价单位，传id或者code
            saleReturnDetailsJson.put("masterUnitId", unitId);  // 主计量单位，传id或者code
            saleReturnDetailsJson.put("invExchRate", 1);  // 销售换算率 BigDecimal
            saleReturnDetailsJson.put("subQty", qty);  // 退货销售数量 BigDecimal
            saleReturnDetailsJson.put("invPriceExchRate", 1);  // 计价换算率 BigDecimal
            saleReturnDetailsJson.put("priceQty", qty);  // 退货计价数量 BigDecimal
            saleReturnDetailsJson.put("qty", qty);  // 退货数量 BigDecimal
            saleReturnDetailsJson.put("oriTaxUnitPrice", unitPriceIncludingTax);  // 含税成交价 BigDecimal
            saleReturnDetailsJson.put("oriUnitPrice", taxFreeUnitPrice);  // 无税单价  BigDecimal
            saleReturnDetailsJson.put("oriSum", saleAmount);  // 含税金额  BigDecimal
            saleReturnDetailsJson.put("oriMoney", noTaxSaleAmount);  // 无税金额  BigDecimal
            saleReturnDetailsJson.put("oriTax", taxAmount);  // 税额  BigDecimal
            saleReturnDetailsJson.put("natTaxUnitPrice", unitPriceIncludingTax);  // 本币含税单价  BigDecimal
            saleReturnDetailsJson.put("natUnitPrice", taxFreeUnitPrice);  // 本币无税单价  BigDecimal
            saleReturnDetailsJson.put("natSum", saleAmount);  // 本币含税金额  BigDecimal
            saleReturnDetailsJson.put("natMoney", noTaxSaleAmount);  // 本币无税金额  BigDecimal
            saleReturnDetailsJson.put("natTax", taxAmount);  // 本币税额  BigDecimal
            saleReturnDetailsJson.put("_status", "Insert");  // 操作标识
            details.add(saleReturnDetailsJson);
        }
        saleReturnSaveMap.put("saleReturnDetails", details);
        saleReturnSaveMap.put("payMoney", payMoney);
        data.put("data", saleReturnSaveMap);
        /*data.put("resubmitCheckKey","11121212111121");
        ReSubmitUtil.resubmitCheckKey(data);*/
        return data;
    }

    private List<JSONObject> sendWdtByQm(Map<String, Object> map,QueryDto dto) throws Exception {
        // 根据客户查询旺店通店铺配置信息
     /*   Object o = RedisUtils.get(dto.getTenantId() + ":2BCust");
        if (o==null){
            InsertLogger(JOB_CLASS,null, "0", "YS销售退货查询失败，未找到2B客户");
        }
        List<JSONObject> shoplist = JSONUtil.toList(JSONUtil.toJsonStr(o), JSONObject.class);
        List<String> shopNos = shoplist.stream().map(obj ->obj.getStr("code")).collect(Collectors.toList());*/
        // 根据客户查询旺店通店铺配置信息
        //自定义档案列表查询
        HashMap<String, String> custData = YsQueryUtil.getFhdpDef(dto,yonsuiteService);
        ArrayList<String> collect = new ArrayList<>();
        for (String s : custData.keySet()) {
            collect.add(custData.get(s));
        }
        List<String> shopNos=new ArrayList<>();
        shopNos.add("NJ004");
        shopNos.add("ND001");
        shopNos.add("NT005");
        shopNos.add("Z0001");
        shopNos.add("NX002");
        shopNos.addAll(collect);
      //  List<JSONObject> resList = new ArrayList<>();
        List<JSONObject> toReceiveRedList = new ArrayList<>();
        DefaultQimenCloudClient client = new DefaultQimenCloudClient(configProperties.getQmServerUrl(), configProperties.getQmAppKey(), configProperties.getQmAppSecret(), "json");
        Integer realityPageNo = 0;
        map.put("page_no", realityPageNo.toString());
        map.put("page_size", "100");
        map.put("process_status", 80);
        boolean hasNext = true;
        //总页数
        Integer totalPage = 0;
        //总条数
        Integer total_count = 0;
        while (hasNext) {
            map.put("page_no", realityPageNo.toString());
            WdtRefundQueryRequest req = this.setModel(map, configProperties.getQmTargetAppKey(), configProperties.getSid());
            WdtRefundQueryResponse res = null;
            try {
                res = client.execute(req);
            } catch (com.yonyou.wdt.qimenmodel.taobao.api.ApiException e) {
                throw new RuntimeException(e);
            }
            JSONObject saleOutJson = JSONUtil.parseObj(res.getBody()).getJSONObject("response");
            if ("0".equals(saleOutJson.getStr("errorcode"))) {
                //判断分页
                if (realityPageNo == 0) {
                    total_count = saleOutJson.getInt("total_count", 0);
                    totalPage = total_count % 100 == 0 ? total_count / 100 : total_count / 100 + 1;
                }
                //每页订单列表
                JSONArray orderArray = saleOutJson.getJSONArray("trade_list");
                if (orderArray.size() > 0) {
                    //resList.addAll(JSONUtil.toList(orderArray,JSONObject.class));

                    List<JSONObject> list = JSONUtil.toList(orderArray, JSONObject.class);
                    for (JSONObject entries : list) {
                        Boolean flag=false;
                        for (String shopNo : shopNos) {
                            if (shopNo.equals(entries.getStr("shop_no"))){
                                flag=true;
                                break;
                            }
                        }
                        if (!flag){
                            Boolean isToReceive=false;
                           JSONArray jsonArray = entries.getJSONArray("goods_list");
                            JSONArray objects = new JSONArray();
                            for (Object o : jsonArray) {
                                JSONObject entries1 = JSONUtil.parseObj(o);
                                if (BigDecimal.ZERO.compareTo(entries1.getBigDecimal("stockin_num"))==0){
                                    isToReceive=true;
                                    break;
                                }
                            }
                            entries.set("refund_order_list",objects);
                            if ((2==entries.getInt("type") || 3==entries.getInt("type") || isToReceive)){
                                toReceiveRedList.add(entries);
                            }
                        }
                    }
                    //resList = groupBy(resList);
                }
                //判断分页
                if (realityPageNo == 0) {
                    total_count = saleOutJson.getInt("total_count", 0);
                    totalPage = total_count % 100 == 0 ? total_count / 100 : total_count / 100 + 1;
                }
                if (totalPage > realityPageNo + 1) {
                    realityPageNo += 1;
                } else {
                    hasNext = false;
                }
            } else {
                InsertLogger(JOB_CLASS,null, "0", "旺店通退货入库接口查询失败" + saleOutJson.getStr("sub_message"));
                break;
            }
        }
        return toReceiveRedList;
    }

    public WdtRefundQueryRequest setModel(Map param, String targetAppKey, String sid) {
        WdtRefundQueryRequest req = new WdtRefundQueryRequest();
        //旺店通的奇门appkey
        req.setTargetAppKey(targetAppKey);
        //旺店通erp的卖家账号
        req.setSid(sid);
        String startTime = MapUtil.getStr(param, "Start");
        if (StringUtils.isNotBlank(startTime)) {
            req.setStartTime(startTime);
        }
        String endTime = MapUtil.getStr(param, "End");
        if (StringUtils.isNotBlank(endTime)) {
            req.setEndTime(endTime);
        }
        String stockinNo = MapUtil.getStr(param, "refund_no");
        if (StringUtils.isNotBlank(stockinNo)) {
            req.setRefundNo(stockinNo);
        }
        String srcOrderNo = MapUtil.getStr(param, "src_order_no");
        if (StringUtils.isNotBlank(srcOrderNo)) {
            req.setSrcOrderNo(srcOrderNo);
        }
        String shop_no = MapUtil.getStr(param, "shop_no");
        if (StringUtils.isNotBlank(shop_no)) {
            req.setShopNo(shop_no);
        }
        if (param.containsKey("page_no")) {
            req.setPageNo(MapUtil.getLong(param, "page_no"));
        }
        if (param.containsKey("page_size")) {
            req.setPageSize(MapUtil.getLong(param, "page_size"));
        }
        if (param.containsKey("status")) {
            req.setProcessStatus(MapUtil.getLong(param, "status"));
        }
        if (param.containsKey("shop_nos")) {
            req.setShopNos(MapUtil.getStr(param, "shop_nos"));
        }
        //req.setTimeType(2L);
        return req;
    }
}
